#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "pthread.h"
/* linux多线程同步-------互斥锁 */
/* 定义互斥量相关*/
pthread_mutex_t task_mutex;
/* 线程任务函数 */
void *pthread_Task(void *data)
{
    pthread_detach(pthread_self()); //线程分离
    while (1)
    {
        /* code */
        pthread_mutex_lock(&task_mutex); //加锁
        printf("%ld thread is running\n", pthread_self());
        pthread_mutex_unlock(&task_mutex);
        sleep(1);
    }
    pthread_exit(0);
}
int tick_num = 10001;
void *pthread_Task_test(void *data)
{
    pthread_detach(pthread_self());
    int thread_num = *(int *)data;
    while (1)
    {
        pthread_mutex_lock(&task_mutex);//加锁
        if (tick_num > 0)
        {
            /* code */
            usleep(1000);
            tick_num--;
            printf("thread %d 抢到了一张票，还剩 %d 张票\n", thread_num, tick_num);
            
            pthread_mutex_unlock(&task_mutex);//释放锁
        }
        else
        {
            pthread_mutex_unlock(&task_mutex);//释放锁
            break;
        }  
        usleep(1000);
    }
    pthread_exit(NULL);
}
/* 线程退出方式
return 0:整个进程直接直接，系统回收资源，把子线程也回收了，所以，这种方式下，主线程退出，子线程也就结束了
pthread_exit(NULL):线程退出，进程并没有结束
 */
int main(int argc, char const *argv[])
{
    /* code */
    /* 创建线程 */
    pthread_t task1;
    pthread_t task2;
    pthread_t tasks[5];
    int task_ret = 0;
    int mutex_ret = 0;
    /*初始化互斥量*/
    mutex_ret = pthread_mutex_init(&task_mutex, NULL);
    if (mutex_ret == -1)
    {
        perror("pthread_mutex_init\n");
    }
    /*  task_ret = pthread_create(&task1, NULL, pthread_Task, NULL);
    if (task_ret == -1)
    {
        perror("pthread_create\n");
    }
    task_ret = pthread_create(&task2, NULL, pthread_Task, NULL);
    if (task_ret == -1)
    {
        perror("pthread_create\n");
    } */
    for (size_t i = 0; i < 5; i++)
    {
        /* code */
        task_ret = pthread_create(&tasks[i], NULL, pthread_Task_test, (void *)&i);
        if (task_ret == -1)
        {
            perror("pthread_create\n");
        }
    }
    // while(1);
    sleep(3);
    pthread_exit(NULL); 
   
    return 0;
}
